package com.libbase.http

import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response

/**
 * 根据请求头设置Tag的名字,这个设置在retrofit的API请求头设置Tag
 */
class HttpTagInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val original = chain.request()
        val headers = original.headers()
        headers.get("Tag")?.let {
            val builder = original.newBuilder()
            builder.tag(it)
            return chain.proceed(builder.build())
        }
        return chain.proceed(original)
    }
}


/**
 * 根据tag取消请求过程
 */
fun cancelTag(tag: String?) {
    tag?.let {
        val callFactory = Http.getInstance().retrofit.callFactory()
        if (callFactory is OkHttpClient) {
            val dispatcher = callFactory.dispatcher()
            for (call in dispatcher.queuedCalls()) {
                if (it == call.request().tag()) {
                    call.cancel()
                }
            }
            for (call in dispatcher.runningCalls()) {
                if (it == call.request().tag()) {
                    call.cancel()
                }
            }
        }
    }
}